package com.dingup.api.template.message.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingup.api.template.message.bean.WxTemplateBean;
import com.suyeer.basic.util.BDateUtil;
import com.suyeer.basic.util.BHttpResUtil;
import com.suyeer.basic.util.BJsonUtil;
import com.suyeer.basic.util.BLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by jun on 2018/7/17.
 */
public class WxMsgUtil {

    private static final int SUCCESS_CODE = 200;
    private static final String KEY_CODE = "code";
    private static final String KEY_ERR_CODE = "errcode";
    private static final String KEY_RESULT = "result";
    private static final String IBT_URL_GET_ACCESS_TOKEN = "https://ibt.topschool.com/wx/get_data.do?key=MC_WX_ACCESS_TOKEN_KEY";
    private static final String WX_URL_SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    private static Logger logger = LoggerFactory.getLogger(WxMsgUtil.class);

    public static void sendMsg(WxTemplateBean wxTemplateBean) throws Exception {
        String url = WX_URL_SEND_TEMPLATE_MESSAGE + getAccessToken();
        try {
            JSONObject ret = BHttpResUtil.sendSSLPostRequest(url, BJsonUtil.toString(wxTemplateBean));
            logger.info("微信 返回: {}", JSON.toJSONString(ret));
            if (ret.getIntValue(KEY_ERR_CODE) != 0) {
                throw new Exception(String.format("微信 返回: {}", JSON.toJSONString(ret)));
            }
        } catch (Exception e) {
            throw new Exception(String.format("发送微信模板消息失败, 失败信息: %s", e.getMessage()));
        }
    }

    private static String getAccessToken() throws Exception {
        String retStr;
        try {
            JSONObject obj = BHttpResUtil.sendHttpPostRequest(IBT_URL_GET_ACCESS_TOKEN, new JSONObject());
            if (obj == null || obj.getIntValue(KEY_CODE) != SUCCESS_CODE) {
                throw new Exception(String.format("IBT 返回: {}", JSON.toJSONString(obj)));
            }
            retStr = obj.getString(KEY_RESULT);
        } catch (Exception e) {
            throw new Exception(String.format("从 IBT 获取微信 AccessToken 失败, 失败信息: %s", e.getMessage()));
        }
        return retStr;
    }

    /**
     * User: jun
     * Date: 2018/7/17
     * Desc: 微信模板消息样例
     */
    private static void demo() {
        WxTemplateBean fwTemplateBean = new WxTemplateBean();
        fwTemplateBean.setUrl("https://ibt.topschool.com");
        fwTemplateBean.setTemplate_id("LXgdpp2JM_HP67RuDaJyY9Sx5idIe5TzYDp7pLsrlBQ");
        fwTemplateBean.addItem("first", BDateUtil.getDateStr(new Date()), "#4e72b8");
        fwTemplateBean.addItem("keyword1", "新排课程", "#4e72b8");
        fwTemplateBean.addItem("keyword2", "请以实际上课时间为准", "#4e72b8");
        fwTemplateBean.addItem("remark", "请点击详情查看新排的课表, 并点击确认收到!", "#4e72b8");
        try {
            sendMsg(fwTemplateBean);
        } catch (Exception e) {
            BLogUtil.error("发送模板消息失败, {}", e.getMessage());
        }
    }
}
